using System;
using System.Web.UI.WebControls;

using SBPweb.Data;

namespace SBPweb.Controls.Web
{
	public delegate void EntityGridViewCommandEventHandler(object sender, EntityGridViewCommandEventArgs e);

	public class EntityGridViewCommandEventArgs : GridViewCommandEventArgs
	{

		#region Private fields

		private Entity mEntity;
		private EntityGridViewCommandType mType;
		private int mIndex;

		#endregion

		#region Constructor logic

		internal EntityGridViewCommandEventArgs(GridViewRow row, object source, string commandName, object argument, Entity entity)
			: base(row, source, new CommandEventArgs(commandName, argument))
		{
			mEntity = entity;
			mType = GetCommandType(commandName);
			mIndex = GetCommandIndex(argument);
		}

		internal EntityGridViewCommandEventArgs(GridViewCommandEventArgs originalArgs, Entity entity)
			: base(originalArgs.CommandSource, originalArgs)
		{
			mEntity = entity;
			mType = GetCommandType(originalArgs.CommandName);
			mIndex = GetCommandIndex(originalArgs.CommandArgument);
		}

		#endregion

		#region Internal static helper methods

		internal static EntityGridViewCommandType GetCommandType(string commandName)
		{
			try
			{
				return (EntityGridViewCommandType)Enum.Parse(typeof(EntityGridViewCommandType), commandName);
			}
			catch
			{
				return EntityGridViewCommandType.Unknown;
			}
		}

		internal static int GetCommandIndex(object commandArgument)
		{
			try
			{
				return Convert.ToInt32(commandArgument);
			}
			catch
			{
				return -1;
			}
		}

		#endregion

		#region Public property accessors

		public Entity SelectedEntity
		{
			get
			{
				return mEntity;
			}
			protected internal set
			{
				mEntity = value;
			}
		}

		public EntityGridViewCommandType CommandType
		{
			get
			{
				return mType;
			}
		}

		public int SelectedIndex
		{
			get
			{
				return mIndex;
			}
		}

		#endregion

	}

}